<template>
  <div class="tag-posts-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/">首页</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>标签</a-breadcrumb-item>
        <a-breadcrumb-item>{{ tag?.name || '加载中...' }}</a-breadcrumb-item>
      </a-breadcrumb>
      
      <div class="tag-info" v-if="tag">
        <div class="tag-header">
          <a-tag :color="tag.color || 'blue'" class="tag-badge">
            {{ tag.name }}
          </a-tag>
        </div>
        <h1>{{ tag.name }}</h1>
        <p v-if="tag.description">{{ tag.description }}</p>
        <div class="tag-stats">
          共 {{ tag.postCount || 0 }} 篇文章
        </div>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="posts-section">
      <a-spin :spinning="loading">
        <div v-if="posts.length === 0 && !loading" class="empty-state">
          <a-empty description="该标签下暂无文章" />
        </div>
        
        <div v-else class="posts-list">
          <div 
            v-for="post in posts" 
            :key="post.id"
            class="post-item"
            @click="viewPost(post.id)"
          >
            <div class="post-content">
              <h3 class="post-title">{{ post.title }}</h3>
              <p class="post-excerpt">{{ post.excerpt }}</p>
              <div class="post-meta">
                <span class="post-date">
                  <CalendarOutlined />
                  {{ formatDate(post.createdAt) }}
                </span>
                <span class="post-views">
                  <EyeOutlined />
                  {{ post.viewCount || 0 }}
                </span>
                <span class="post-comments">
                  <CommentOutlined />
                  {{ post.commentCount || 0 }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </a-spin>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="posts.length > 0">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          show-size-changer
          show-quick-jumper
          @change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  CalendarOutlined, 
  EyeOutlined,
  CommentOutlined
} from '@ant-design/icons-vue'
import { postApi, tagApi } from '@/api'
import type { Post, Tag } from '@/types'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const posts = ref<Post[]>([])
const tag = ref<Tag | null>(null)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 查看文章详情
const viewPost = (postId: number) => {
  router.push(`/post/${postId}`)
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  pagination.current = page
  pagination.pageSize = pageSize
  loadPosts()
}

// 加载标签信息
const loadTag = async () => {
  try {
    const tagId = Number(route.params.id)
    // 这里可能需要添加获取单个标签的API，暂时用列表API模拟
    const response = await tagApi.getTagList({ pageNo: '1', pageSize: '100' })
    const tags = response.data.result || []
    tag.value = tags.find(t => t.id === tagId) || null
    
    if (!tag.value) {
      // 如果没有找到标签，重定向到404页面
      router.push('/404')
    }
  } catch (error) {
    console.error('加载标签信息失败:', error)
  }
}

// 加载文章列表
const loadPosts = async () => {
  loading.value = true
  
  try {
    const tagId = Number(route.params.id)
    const response = await postApi.getPostList({
      pageNo: pagination.current.toString(),
      pageSize: pagination.pageSize.toString(),
      tagId: tagId.toString(),
      status: 'PUBLISHED'
    })
    
    posts.value = response.data.result || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载文章列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载数据
const loadData = async () => {
  await Promise.all([
    loadTag(),
    loadPosts()
  ])
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.tag-posts-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;
}

.tag-header {
  margin-bottom: 8px;
}

.tag-badge {
  font-size: 16px;
  padding: 4px 12px;
}

.page-header h1 {
  font-size: 32px;
  font-weight: 600;
  margin: 16px 0 8px 0;
  color: #262626;
}

.tag-info p {
  color: #8c8c8c;
  font-size: 16px;
  margin-bottom: 16px;
}

.tag-stats {
  color: #595959;
  font-size: 14px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 32px;
}

.post-item {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.post-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.post-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #262626;
}

.post-excerpt {
  color: #8c8c8c;
  line-height: 1.6;
  margin: 0 0 16px 0;
}

.post-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #8c8c8c;
}

.post-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 24px 0;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tag-posts-container {
    padding: 16px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .post-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>